<template>
  <div class="unit-conversion-page">
    <div class="page-header">
      <h2>
        <el-icon><Operation /></el-icon>
        商品单位换算
      </h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加换算
      </el-button>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>单位换算列表</span>
          <el-input
            v-model="searchText"
            placeholder="搜索商品..."
            clearable
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="filteredConversions" stripe>
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column prop="baseUnit" label="基本单位" width="100">
          <template #default="{ row }">
            <el-tag type="success">{{ row.baseUnit }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="换算单位" min-width="300">
          <template #default="{ row }">
            <div class="conversion-list">
              <el-tag
                v-for="(conv, index) in row.conversions"
                :key="index"
                class="conversion-tag"
              >
                1{{ conv.unit }} = {{ conv.rate }}{{ row.baseUnit }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" text @click="handleCalculator(row)">
              计算器
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 单位换算编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="单位换算设置" width="700px">
      <el-form :model="conversionForm" label-width="120px">
        <el-form-item label="商品">
          <el-select v-model="conversionForm.productId" placeholder="请选择商品" style="width: 100%" filterable>
            <el-option
              v-for="product in products"
              :key="product.id"
              :label="`${product.code} - ${product.name}`"
              :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="基本单位">
          <el-select v-model="conversionForm.baseUnit" placeholder="请选择基本单位" style="width: 200px">
            <el-option label="个" value="个" />
            <el-option label="支" value="支" />
            <el-option label="瓶" value="瓶" />
            <el-option label="袋" value="袋" />
            <el-option label="克" value="克" />
            <el-option label="升" value="升" />
          </el-select>
          <span style="margin-left: 10px; color: #909399">作为换算的基准单位</span>
        </el-form-item>

        <el-divider>换算单位配置</el-divider>

        <div
          v-for="(conv, index) in conversionForm.conversions"
          :key="index"
          class="conversion-item"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="换算单位">
                <el-select v-model="conv.unit" placeholder="请选择" style="width: 100%">
                  <el-option label="盒" value="盒" />
                  <el-option label="箱" value="箱" />
                  <el-option label="包" value="包" />
                  <el-option label="件" value="件" />
                  <el-option label="打" value="打" />
                  <el-option label="箩" value="箩" />
                  <el-option label="千克" value="千克" />
                  <el-option label="吨" value="吨" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="换算率">
                <div class="conversion-rate">
                  <span>1{{ conv.unit }} = </span>
                  <el-input-number
                    v-model="conv.rate"
                    :min="0.001"
                    :precision="3"
                    style="width: 150px"
                  />
                  <span>{{ conversionForm.baseUnit }}</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="danger" @click="handleRemoveConversion(index)">
                删除
              </el-button>
            </el-col>
          </el-row>
        </div>

        <el-button type="primary" plain @click="handleAddConversion">
          <el-icon><Plus /></el-icon>
          添加换算单位
        </el-button>

        <el-divider>换算示例</el-divider>
        <el-alert
          v-if="conversionExample"
          :title="conversionExample"
          type="info"
          :closable="false"
        />
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 单位换算计算器 -->
    <el-dialog v-model="calculatorVisible" title="单位换算计算器" width="500px">
      <div class="calculator">
        <el-form label-width="100px">
          <el-form-item label="商品">
            <strong>{{ currentProduct.productName }}</strong>
          </el-form-item>

          <el-divider />

          <el-form-item label="输入数量">
            <el-input-number
              v-model="calculator.fromQuantity"
              :min="0"
              :precision="3"
              style="width: 150px"
            />
            <el-select v-model="calculator.fromUnit" style="width: 100px; margin-left: 10px">
              <el-option :label="currentProduct.baseUnit" :value="currentProduct.baseUnit" />
              <el-option
                v-for="(conv, index) in currentProduct.conversions"
                :key="index"
                :label="conv.unit"
                :value="conv.unit"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div class="conversion-result">
              <el-icon size="large"><Bottom /></el-icon>
            </div>
          </el-form-item>

          <el-form-item label="换算结果">
            <div class="result-box">
              <div class="result-item" v-for="(result, index) in calculatorResults" :key="index">
                <span class="result-value">{{ result.quantity }}</span>
                <span class="result-unit">{{ result.unit }}</span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="calculatorVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleResetCalculator">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Operation, Plus, Search, Bottom } from '@element-plus/icons-vue'

const searchText = ref('')
const dialogVisible = ref(false)
const calculatorVisible = ref(false)

const products = ref([
  { id: 1, code: 'P001', name: 'iPhone 15' },
  { id: 2, code: 'P002', name: 'MacBook Pro' }
])

const unitConversions = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15',
    baseUnit: '个',
    conversions: [
      { unit: '盒', rate: 1 },
      { unit: '箱', rate: 10 }
    ]
  },
  {
    id: 2,
    productCode: 'P002',
    productName: 'MacBook Pro',
    baseUnit: '台',
    conversions: [
      { unit: '箱', rate: 1 },
      { unit: '托', rate: 20 }
    ]
  }
])

const currentProduct = ref({})

const conversionForm = reactive({
  id: null,
  productId: null,
  baseUnit: '',
  conversions: [
    { unit: '', rate: 1 }
  ]
})

const calculator = reactive({
  fromQuantity: 1,
  fromUnit: '',
  toUnit: ''
})

const filteredConversions = computed(() => {
  if (!searchText.value) return unitConversions.value
  return unitConversions.value.filter(conv =>
    conv.productName.includes(searchText.value) ||
    conv.productCode.includes(searchText.value)
  )
})

const conversionExample = computed(() => {
  if (conversionForm.conversions.length === 0) return ''
  const examples = conversionForm.conversions
    .filter(c => c.unit && c.rate)
    .map(c => `1${c.unit} = ${c.rate}${conversionForm.baseUnit}`)
  return examples.length > 0 ? `示例：${examples.join('；')}` : ''
})

const calculatorResults = computed(() => {
  if (!calculator.fromQuantity || !calculator.fromUnit || !currentProduct.value.conversions) return []

  // 先转换到基本单位
  let baseQuantity = calculator.fromQuantity
  if (calculator.fromUnit !== currentProduct.value.baseUnit) {
    const fromConv = currentProduct.value.conversions.find(c => c.unit === calculator.fromUnit)
    if (fromConv) {
      baseQuantity = calculator.fromQuantity * fromConv.rate
    }
  }

  // 计算所有单位的换算结果
  const results = [
    { unit: currentProduct.value.baseUnit, quantity: baseQuantity.toFixed(3) }
  ]

  currentProduct.value.conversions.forEach(conv => {
    if (conv.unit !== calculator.fromUnit) {
      const quantity = baseQuantity / conv.rate
      results.push({ unit: conv.unit, quantity: quantity.toFixed(3) })
    }
  })

  return results
})

const handleAdd = () => {
  Object.assign(conversionForm, {
    id: null,
    productId: null,
    baseUnit: '',
    conversions: [{ unit: '', rate: 1 }]
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(conversionForm, {
    ...row,
    conversions: JSON.parse(JSON.stringify(row.conversions))
  })
  dialogVisible.value = true
}

const handleAddConversion = () => {
  conversionForm.conversions.push({ unit: '', rate: 1 })
}

const handleRemoveConversion = (index) => {
  conversionForm.conversions.splice(index, 1)
}

const handleCalculator = (row) => {
  currentProduct.value = { ...row }
  calculator.fromQuantity = 1
  calculator.fromUnit = row.baseUnit
  calculatorVisible.value = true
}

const handleResetCalculator = () => {
  calculator.fromQuantity = 1
  calculator.fromUnit = currentProduct.value.baseUnit
}

const handleSubmit = () => {
  ElMessage.success('保存成功')
  dialogVisible.value = false
}
</script>

<style scoped>
.unit-conversion-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.conversion-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.conversion-tag {
  margin: 0;
}

.conversion-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.conversion-rate {
  display: flex;
  align-items: center;
  gap: 10px;
}

.calculator {
  padding: 20px 0;
}

.conversion-result {
  text-align: center;
  padding: 10px 0;
}

.result-box {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.result-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 4px;
  border: 2px solid #409eff;
}

.result-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
}

.result-unit {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}
</style>

